<template>
  <div class="category">
    <div class="search">
      <el-form ref="searchForm" v-loading="listLoading" :model="searchForm" inline>
        <!-- <el-form-item label="用户ID" prop="id">
          <el-input
            v-model.trim="searchForm.id"
            placeholder="用户ID"
            class="input"
            clearable
          />
        </el-form-item> -->

        <!-- <el-form-item label="用户状态：" prop="status">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="隐藏" value="0" />
            <el-option label="正常" value="1" />
          </el-select>
        </el-form-item> -->

        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model.trim="searchForm.nickName" placeholder="用户昵称" class="input" clearable />
        </el-form-item>

        <!-- <el-form-item>
          <el-button type="primary" size="medium" @click="searchData">
            搜索
          </el-button>
          <el-button type="primary" size="medium" @click="resetSearchData">
            重置
          </el-button>
        </el-form-item> -->
      </el-form>
    </div>

    <div class="app-container">
      <el-table v-loading="listLoading"
        :data="filter().slice((searchForm.page - 1) * searchForm.pageSize, searchForm.page * searchForm.pageSize)"
        element-loading-text="Loading" border fit highlight-current-row>

        <el-table-column label="用户名称" align="center">
          <template slot-scope="scope">
            {{ scope.row.nickName }}
          </template>
        </el-table-column>
        <el-table-column label="用户手机" align="center">
          <template slot-scope="scope">
            {{ scope.row.phone }}
          </template>
        </el-table-column>
        <el-table-column label="用户密码" align="center">
          <template slot-scope="scope">
            {{ md5(scope.row.password) }}
          </template>
        </el-table-column>
        <el-table-column label="用户积分" align="center">
          <template slot-scope="scope">
            {{ scope.row.balance }}
          </template>
        </el-table-column>
        <el-table-column label="禁用/启用" align="center">
          <template slot-scope="scope">

            <el-button v-if="scope.row.stop" size="mini" type="text" @click="palyerStop(scope.row)">禁用</el-button>
            <el-button v-if="!scope.row.stop" size="mini" type="text" @click="palyerStop(scope.row)">启用</el-button>

            <!-- <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button> -->
          </template>
        </el-table-column>
        <!-- <el-table-column class-name="status-col" label="在线状态" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status | statusFilter">{{
              scope.row.status | statusFilterText
            }}</el-tag>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="primary" @click="chongzhi(scope.row)">积分充值</el-button>
            <!-- <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <el-dialog title="充值积分" :visible.sync="dialogFormVisible">
        <el-form :model="dealobj">
          <el-form-item label="积分">
            <el-input v-model="dealobj.value" type="number"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </div>
      </el-dialog>

      <div class="pagination">
        <el-pagination background :current-page.sync="searchForm.page" layout="total, prev, pager, next"
          :total="filter().length" @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
</template>

<script>
import { getUserList, deleteUser } from '@/api/user'
import crypto from 'crypto'
import dealApi from '@/plugins/api/deal'
import userApi from '@/plugins/api/user'
import { fuzzyMatch } from '@/plugins/utils/filterArray'

export default {
  name: 'UserList',
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'danger',
        1: 'success'
      }
      return statusMap[status]
    },
    statusFilterText(status) {
      const statusMap = {
        0: '禁用',
        1: '正常'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      listLoading: true,
      count: 0,
      searchForm: {
        nickName: '',
        phone: '',
        role: 1,
        page: 1,
        pageSize: 10,
      },
      dialogFormVisible: false,
      currentUser: {},
      dealobj: {
        userId: null,
        value: 0,
        createTime: null,
        type: 4,
        yuanyin: ''
      },
    }
  },
  mounted() {
    this.fetchData()
  },
  methods: {
    // 禁止用户操作
    async palyerStop(row) {
      const p = row
      p.stop = !p.stop
      console.log(p)
      const res = await userApi.update(p)
      console.log(res)
      if (res.code === 200) {
        this.$message.success('操作成功')
        this.getUsers()
      }else {
        this.$message.error(res.msg)
      }
    },

    filter() {
      return fuzzyMatch(this.list, this.searchForm)
    },
    md5(text) {
      return crypto.createHash('md5').update(text).digest('hex')
    },

    async submit() {
      const that = this
      that.dealobj.createTime = new Date().getTime()
      that.currentUser.balance = (Number(that.currentUser.balance) + Number(that.dealobj.value)).toFixed(2)
      console.log(that.dealobj);

      const res = await userApi.update(that.currentUser)
      if (res.code === 200) {
        const fakuanres = await dealApi.modify(that.dealobj)
        if (fakuanres.code === 200) {
          that.$message.success('充值成功')
          that.fetchData()
          that.dialogFormVisible = false
        } else {
          that.$message.error(fakuanres.msg)
        }
      } else {
        that.$message.error(res.msg)
      }

    },

    // 获取用户信息
    async fetchData() {
      try {
        this.listLoading = true
        const res = await userApi.all()
        console.log('res -> ', res);
        this.list = res.data
      } catch (err) {
        console.log(err)
      } finally {
        this.listLoading = false
      }
    },

    chongzhi(row) {
      this.dealobj.userId = row.id
      this.currentUser = row
      this.dialogFormVisible = true
    },

    // 跳转编辑
    handleEdit(row) {
      localStorage.setItem('huiyuan', JSON.stringify(row))
      this.$router.push('/user/edit')
    },
    // 删除用户
    handleDelete(id) {
      try {
        this.$msgbox
          .confirm('确定需要删除这个用户吗', '提示', {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'error'
          })
          .then(async () => {
            const r = await deleteUser({ id })
            this.$message.success(r.msg)
            await this.fetchData()
          })
      } catch (err) {
        this.$message.error(err)
      }
    },
    // 搜索
    searchData() {
      this.searchForm.page = 1
      this.searchForm.role = 1
    },
    // 点击页面
    handleCurrentChange(page) {
      this.searchForm.page = page
      // this.fetchData()
    },
    // 重置表单
    resetSearchData() {
      this.$refs['searchForm'].resetFields()
      this.fetchData()
    }
  }
}
</script>

<style scoped lang="scss">
.category {
  box-sizing: border-box;
  margin: 24px;
}

.search {
  box-sizing: border-box;
  border-bottom: 1px solid #f0f0f0;
}

.pagination {
  display: flex;
  justify-content: center;
  margin: 24px 0;
}
</style>
